package megrez.job.custom.component;

import java.util.concurrent.ScheduledFuture;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

/**
 * 计划任务运行对象持有
 *  
 * @author Lucky Yang
 * @since 2.6.9
 */
@Slf4j
public class ScheduledFutureTaskHolder {
    private final ScheduledFuture<?> future;
    private final ScheduledTask scheduledTask;
    @Getter
    private volatile boolean stopped = false;
    
    public ScheduledFutureTaskHolder(ScheduledTask scheduledTask, ScheduledFuture<?> future) {
        this.scheduledTask = scheduledTask;
        this.future = future;
    }

    protected ScheduledFutureTaskHolder(boolean stopped) {
        this(null, null);
        this.stopped = stopped;
    }

    /** 空哨兵，避免其他地方null判断 */
    public static ScheduledFutureTaskHolder emptyHolder() {
        return new ScheduledFutureTaskHolder(true);
    }

    /**
     * 停止定时任务
     */
    public void stop() {
        if (stopped) {
            log.warn("The task has been stopped. Don't stop it again");
        }

        stopped = true;
        if (future != null) {
            future.cancel(true);
        } 
        scheduledTask.stop();
    }
    
    public void start() {
        if (stopped) {
            log.warn("The task has stopped and cannot be started again");
            return;
        }
        scheduledTask.start();
    }


}
